/* ASt tree interpreter. */

#include "defs.h"
#include "data.h"
#include "decl.h"

/*
 * List of AST operators.
 */
static char *ASTop[] = {"+", "-", "*", "/"};

/*
 * Given an AST, interpret the operators in it
 * and return final value.
 */
int interpretAST(struct ASTnode *node)
{
    int left_val, right_val;

    // get the left and right sub-tree values
    if (node->left)
        left_val = interpretAST(node->left);
    if (node->right)
        right_val = interpretAST(node->right);

#ifdef DEBUG
    if (node->op == A_INTLIT)
        printf("int %d\n", node->intvalue);
    else
        printf("%d %s %d\n", left_val, ASTop[node->op], right_val);
#endif // DEBUG

    switch (node->op) {
    case A_ADD:
        return (left_val + right_val);
    case A_SUBSTRACT:
        return (left_val - right_val);
    case A_MULTIPLY:
        return (left_val * right_val);
    case A_DIVIDE:
        return (left_val / right_val);
    case A_INTLIT:
        return node->v.intvalue;
    default:
        fprintf(stderr, "Unknown AST operator %d\n", node->op);
        exit(1);
    }
}
